import React, { useState, useEffect } from 'react';
import { Layout, Menu, Button, Dropdown, Avatar, Space, Typography, Progress, Drawer } from 'antd';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  DashboardOutlined,
  EnvironmentOutlined,
  SettingOutlined,
  DatabaseOutlined,
  GlobalOutlined,
  BulbOutlined,
  UserOutlined,
  LogoutOutlined,
  MoreOutlined,
} from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useThemeConfig } from '../contexts/ThemeConfigContext';
import { useAuth } from '../contexts/AuthContext';
import { useMessage } from '../contexts/MessageContext';
import { NavigationProvider } from '../contexts/NavigationContext';
import { getTopMenuItems, getSideMenuItems } from '../config/routes';
import TabBar from '../components/TabBar/TabBar';
import useTabStore from '../stores/tabStore';
import ThemeSettings from '../components/ThemeSettings/ThemeSettings';

const { Header, Sider, Content } = Layout;
const { Text } = Typography;

const MixedLayout = ({ children }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const { t, i18n } = useTranslation();
  const { isDark, toggleTheme, currentColors, showDemoFeatures } = useThemeConfig();
  const { addTab, getTabConfig } = useTabStore();

  // 页面切换状态
  const [isLoading, setIsLoading] = useState(false);
  const [loadingProgress, setLoadingProgress] = useState(0);
  const [currentPath, setCurrentPath] = useState(location.pathname);
  const [animationState, setAnimationState] = useState('idle');
  const [nextPath, setNextPath] = useState(null);
  const [collapsed, setCollapsed] = useState(false);
  const [themeSettingsOpen, setThemeSettingsOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);

  // 从路由配置生成菜单项
  const topMenuItems = getTopMenuItems(t, showDemoFeatures);
  const sideMenuItems = getSideMenuItems(location.pathname, t, showDemoFeatures);

  // 语言切换菜单
  const languageMenuItems = [
    {
      key: 'zh-CN',
      label: t('settings.chinese'),
    },
    {
      key: 'en-US',
      label: t('settings.english'),
    },
  ];

  // 用户菜单
  const userMenuItems = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人资料',
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      danger: true,
    },
  ];

  // 检测是否为移动设备宽度
  const checkIsMobile = () => {
    const width = window.innerWidth;
    return width < 768; // 768px 以下认为是移动设备
  };

  // 处理窗口大小变化
  const handleResize = () => {
    const mobile = checkIsMobile();
    setIsMobile(mobile);

    // 在移动设备上自动收缩侧边栏和关闭抽屉
    if (mobile) {
      if (!collapsed) {
        setCollapsed(true);
      }
      if (drawerVisible) {
        setDrawerVisible(false);
      }
    }
  };

  // 响应式监听器
  useEffect(() => {
    // 初始检测
    handleResize();

    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [collapsed]);

  // 模拟加载进度
  const simulateLoadingProgress = () => {
    setLoadingProgress(0);
    const interval = setInterval(() => {
      setLoadingProgress(prev => {
        if (prev >= 100) {
          clearInterval(interval);
          setTimeout(() => {
            setIsLoading(false);
            setLoadingProgress(0);
          }, 200);
          return 100;
        }
        return prev + Math.random() * 30;
      });
    }, 100);
  };

  // 处理菜单点击 - 轻量级动画版本
  const handleMenuClick = ({ key }) => {
    if (key !== currentPath) {
      const tabConfig = getTabConfig(key);
      if (tabConfig) {
        addTab(key);
      }

      // 添加简单的页面切换动画
      setAnimationState('switching');
      setCurrentPath(key);
      navigate(key);

      // 在移动设备上点击菜单后自动关闭抽屉
      if (isMobile && drawerVisible) {
        setDrawerVisible(false);
      }

      // 短暂延迟后重置动画状态
      setTimeout(() => {
        setAnimationState('idle');
      }, 300);
    }
  };

  // 处理点击内容区域，在移动设备上隐藏侧边栏
  const handleContentClick = () => {
    if (isMobile && !collapsed) {
      setCollapsed(true);
    }
  };

  const toggleDrawer = () => {
    setDrawerVisible(!drawerVisible);
  };

  // 监听路由变化 - 合并所有路由相关逻辑
  useEffect(() => {
    if (location.pathname !== currentPath) {
      setCurrentPath(location.pathname);

      // 同步Tab系统
      const tabConfig = getTabConfig(location.pathname);
      if (tabConfig) {
        addTab(location.pathname);
      }
    }
  }, [location.pathname, currentPath, addTab, getTabConfig]);

  const handleLanguageChange = ({ key }) => {
    i18n.changeLanguage(key);
  };

  const { logout, user } = useAuth();
  const { showMessage } = useMessage();

  const handleUserMenuClick = ({ key }) => {
    if (key === 'logout') {
      logout();
      showMessage('success', '已安全退出登录');
      navigate('/login');
    }
  };

  const toggleSidebar = () => setCollapsed(!collapsed);

  return (
    <Layout style={{ height: '100vh', overflow: 'hidden' }}>
      {/* 精致的顶部加载条 */}
      {isLoading && (
        <div
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            zIndex: 9999,
            height: 2,
            background: isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)',
          }}
        >
          <div
            style={{
              height: '100%',
              background: 'linear-gradient(90deg, #1890ff, #40a9ff)',
              width: `${loadingProgress}%`,
              transition: 'width 0.2s cubic-bezier(0.4, 0.0, 0.2, 1)',
              boxShadow: '0 0 10px rgba(24, 144, 255, 0.3)',
            }}
          />
        </div>
      )}

      {/* 顶部Header */}
      <Header
        style={{
          padding: isMobile ? '0 16px' : '0 24px',
          background: currentColors.bg,
          borderBottom: `1px solid ${currentColors.border}`,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
          flexShrink: 0,
          height: 64,
        }}
      >
        {/* 移动端布局 */}
        {isMobile ? (
          <>
            {/* 左侧：汉堡菜单 + Logo */}
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Button
                type="text"
                icon={<MenuUnfoldOutlined />}
                onClick={toggleDrawer}
                style={{
                  fontSize: 18,
                  width: 40,
                  height: 40,
                  marginRight: 12,
                }}
              />
              <Text
                strong
                style={{
                  fontSize: 18,
                  color: isDark ? '#ffffff' : '#1890ff',
                  flexShrink: 0,
                  whiteSpace: 'nowrap',
                }}
              >
                Tree Admin
              </Text>
            </div>

            {/* 右侧：用户头像 */}
            <Dropdown
              menu={{
                items: userMenuItems,
                onClick: handleUserMenuClick,
              }}
              placement="bottomRight"
            >
              <Avatar
                icon={<UserOutlined />}
                style={{
                  cursor: 'pointer',
                  backgroundColor: '#1890ff',
                }}
              />
            </Dropdown>
          </>
        ) : (
          <>
            {/* 桌面端布局 */}
            <div style={{ display: 'flex', alignItems: 'center', flex: 1, minWidth: 0 }}>
              <Button
                type="text"
                icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                onClick={() => setCollapsed(!collapsed)}
                style={{
                  fontSize: 16,
                  width: 40,
                  height: 40,
                  marginRight: 16,
                  color: currentColors.text,
                }}
              />
              <Text
                strong
                style={{
                  fontSize: 20,
                  color: isDark ? '#ffffff' : '#1890ff',
                  marginRight: 24,
                  flexShrink: 0,
                }}
              >
                Tree Admin
              </Text>

              <Menu
                theme={isDark ? 'dark' : 'light'}
                mode="horizontal"
                selectedKeys={[location.pathname.startsWith('/dashboard') ? '/dashboard' : 'management']}
                items={topMenuItems}
                onClick={({ key }) => {
                  // 处理所有有效的路由
                  if (key.startsWith('/')) {
                    handleMenuClick({ key });
                  }
                }}
                style={{
                  border: 'none',
                  background: 'transparent',
                  flex: 1,
                  minWidth: 0,
                }}
                overflowedIndicator={
                  <Button
                    type="text"
                    icon={<MoreOutlined />}
                    style={{
                      border: 'none',
                      boxShadow: 'none',
                      color: currentColors.text,
                      fontSize: '16px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  />
                }
              />
            </div>

            {/* 桌面端右侧操作区 */}
            <Space size="middle" style={{ flexShrink: 0 }}>
              <Button
                type="text"
                icon={<BulbOutlined />}
                onClick={(e) => toggleTheme(e)}
                style={{
                  fontSize: 16,
                  width: 40,
                  height: 40,
                  color: currentColors.text,
                }}
              />

              <Button
                type="text"
                icon={<SettingOutlined />}
                onClick={() => setThemeSettingsOpen(true)}
                style={{
                  fontSize: 16,
                  width: 40,
                  height: 40,
                  color: currentColors.text,
                }}
              />

              <Dropdown
                menu={{
                  items: languageMenuItems,
                  onClick: handleLanguageChange,
                }}
                placement="bottomRight"
              >
                <Button
                  type="text"
                  icon={<GlobalOutlined />}
                  style={{
                    fontSize: 16,
                    width: 40,
                    height: 40,
                    color: currentColors.text,
                  }}
                />
              </Dropdown>

              <Dropdown
                menu={{
                  items: userMenuItems,
                  onClick: handleUserMenuClick,
                }}
                placement="bottomRight"
              >
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <div style={{ textAlign: 'right', marginRight: '8px' }}>
                    <div style={{
                      color: currentColors.text,
                      fontSize: '14px',
                      fontWeight: 500,
                      lineHeight: 1.2
                    }}>
                      {user?.username || '用户'}
                    </div>
                    <div style={{
                      color: currentColors.textSecondary,
                      fontSize: '12px',
                      lineHeight: 1.2
                    }}>
                      {user?.email || 'user@sjly.com'}
                    </div>
                  </div>
                  <Avatar
                    icon={<UserOutlined />}
                    style={{
                      cursor: 'pointer',
                      backgroundColor: '#1890ff',
                    }}
                  />
                </div>
              </Dropdown>
            </Space>
          </>
        )}
      </Header>

      <Layout>
        {/* 桌面端侧边栏 */}
        {!isMobile && (
          <Sider
            trigger={null}
            collapsible
            collapsed={collapsed}
            width={240}
            style={{
              background: currentColors.bgSecondary,
              boxShadow: '2px 0 8px rgba(0,0,0,0.1)',
            }}
          >
            <div
              style={{
                height: 48,
                display: 'flex',
                alignItems: 'center',
                justifyContent: collapsed ? 'center' : 'space-between',
                padding: '0 16px',
                borderBottom: `1px solid ${currentColors.border}`,
              }}
            >
              {!collapsed && (
                <Text
                  strong
                  style={{
                    fontSize: 14,
                    color: currentColors.textSecondary,
                  }}
                >
                  子菜单
                </Text>
              )}
              <Button
                type="text"
                icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                onClick={toggleSidebar}
                style={{
                  fontSize: 16,
                  width: 32,
                  height: 32,
                }}
              />
            </div>

            <Menu
              theme={isDark ? 'dark' : 'light'}
              mode="inline"
              selectedKeys={[location.pathname]}
              items={sideMenuItems}
              onClick={handleMenuClick}
              style={{
                border: 'none',
                background: 'transparent',
                marginTop: 8,
              }}
            />
          </Sider>
        )}

        <Layout
          style={{
            display: 'flex',
            flexDirection: 'column',
            marginLeft: isMobile ? 0 : 'auto', // 移动设备上不需要左边距
          }}
        >
          {/* Tab标签栏 */}
          <div style={{ flexShrink: 0 }}>
            <NavigationProvider onNavigate={handleMenuClick}>
              <TabBar />
            </NavigationProvider>
          </div>

          <Content
            style={{
              margin: '10px',
              padding: 0,
              background: 'transparent',
              borderRadius: 8,
              flex: 1,
              position: 'relative',
              overflow: 'hidden',
              perspective: '1000px',
              minHeight: 0,
            }}
          >
            {/* 翻页容器 */}
            <div
              className="flip-container"
              style={{
                width: '100%',
                height: '100%',
                position: 'relative',
                display: 'flex',
                flexDirection: 'column',
              }}
            >
              {/* 页面内容 - 简化的动画版本 */}
              <div
                className={`page-content ${animationState === 'switching' ? 'page-switching' : ''}`}
                onClick={handleContentClick}
                style={{
                  width: '100%',
                  height: '100%',
                  padding: 16,
                  background: currentColors.bg,
                  borderRadius: 12,
                  overflow: 'auto',
                  display: 'flex',
                  flexDirection: 'column',
                  transition: 'opacity 0.3s ease, transform 0.3s ease',
                  opacity: animationState === 'switching' ? 0.7 : 1,
                  transform: animationState === 'switching' ? 'translateY(10px)' : 'translateY(0)',
                }}
              >
                {children}
              </div>

            </div>
          </Content>
        </Layout>
      </Layout>

      {/* 主题设置 */}
      <ThemeSettings
        open={themeSettingsOpen}
        onClose={() => setThemeSettingsOpen(false)}
      />

      {/* 移动端抽屉菜单 */}
      <Drawer
        title={
          <Text strong style={{ color: currentColors.primary }}>
            Tree Admin
          </Text>
        }
        placement="left"
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        width={280}
        styles={{
          body: {
            padding: 0,
            background: currentColors.bg,
          },
          header: {
            background: currentColors.bg,
            borderBottom: `1px solid ${currentColors.border}`,
          },
        }}
      >
        {/* 菜单项 */}
        <Menu
          theme={isDark ? 'dark' : 'light'}
          mode="vertical"
          selectedKeys={[location.pathname]}
          items={sideMenuItems}
          onClick={handleMenuClick}
          style={{
            border: 'none',
            background: 'transparent',
            marginBottom: 16,
          }}
        />

        {/* 底部操作区 */}
        <div style={{
          padding: '16px',
          borderTop: `1px solid ${currentColors.border}`,
          background: currentColors.bg,
        }}>
          <Space direction="vertical" size="middle" style={{ width: '100%' }}>
            <Button
              type="text"
              icon={<BulbOutlined />}
              onClick={(e) => toggleTheme(e)}
              style={{ width: '100%', textAlign: 'left' }}
            >
              {isDark ? '浅色主题' : '深色主题'}
            </Button>

            <Button
              type="text"
              icon={<SettingOutlined />}
              onClick={() => {
                setThemeSettingsOpen(true);
                setDrawerVisible(false);
              }}
              style={{ width: '100%', textAlign: 'left' }}
            >
              主题设置
            </Button>

            <Dropdown
              menu={{
                items: languageMenuItems,
                onClick: handleLanguageChange,
              }}
              placement="topLeft"
            >
              <Button
                type="text"
                icon={<GlobalOutlined />}
                style={{ width: '100%', textAlign: 'left' }}
              >
                语言切换
              </Button>
            </Dropdown>

            <Button
              type="text"
              icon={<LogoutOutlined />}
              onClick={() => {
                handleUserMenuClick({ key: 'logout' });
                setDrawerVisible(false);
              }}
              style={{ width: '100%', textAlign: 'left' }}
              danger
            >
              退出登录
            </Button>
          </Space>
        </div>
      </Drawer>
    </Layout>
  );
};

export default MixedLayout;
